package com.apkfuns.jsbridge.view.fragment;

import com.apkfuns.jsbridge.JsBridge;
import com.apkfuns.jsbridge.ResourceTable;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.webengine.*;
import ohos.agp.utils.TextTool;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.net.URLConnection;

public class CustomFragment extends Fraction {


    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "CustomFragment");

    private WebView webView;
    private JsBridge jsBridge;

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        Component component = scatter.parse(ResourceTable.Layout_ability_fragment_webview, container, false);
        webView = (WebView) component.findComponentById(ResourceTable.Id_webview);
        return component;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        initWebView();
    }


    @Override
    public void terminateAbility() {
        jsBridge.clean();
        jsBridge.release();
        super.terminateAbility();

    }


    private void initWebView() {
        jsBridge = JsBridge.loadModule();
        webView.getWebConfig().setJavaScriptPermit(true);

        webView.setBrowserAgent(new BrowserAgent(this) {

            @Override
            public boolean onJsMessageShow(WebView w, String url, String message, boolean isAlert, JsMessageResult r) {
                if (jsBridge.callJsPrompt(message, r)) {
                    return true;
                }
                return super.onJsMessageShow(webView, url, message, isAlert, r);
            }

            @Override
            public boolean onJsTextInput(WebView w, String url, String message, String defaultInput, JsTextInputResult r) {
                if (jsBridge.callJsPrompt(message, r)) {
                    return true;
                }
                return super.onJsTextInput(webView, url, message, defaultInput, r);
            }

        });



        webView.setWebAgent(new JsWebAgent());
        webView.load(getFractionAbility().getString(ResourceTable.String_fragment_url));

    }


    class JsWebAgent extends WebAgent{
        @Override
        public ResourceResponse processResourceRequest(WebView w, ResourceRequest request) {
            final String authority = "example.com";
            final String rawFile = "/rawfile/";
            Uri requestUri = request.getRequestUrl();
            if (authority.equals(requestUri.getDecodedAuthority())) {
                String path = requestUri.getDecodedPath();
                if (TextTool.isNullOrEmpty(path)) {
                    return super.processResourceRequest(webView, request);
                }
                if (path.startsWith(rawFile)) {
                    // 根据自定义规则访问资源文件
                    String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
                    String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                    try {
                        Resource resource = getFractionAbility().getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                        return new ResourceResponse(mimeType, resource, null);
                    } catch (IOException e) {
                        HiLog.info(LABEL, "open raw file failed");
                    }
                }
            }
            return super.processResourceRequest(webView, request);
        }

        @Override
        public void onPageLoaded(WebView w, String url) {
            super.onPageLoaded(w, url);
            // 页面加载结束后自定义处理
            jsBridge.injectJs(getFractionAbility(),webView);
        }
    }
}
